"""
编写测试报告消息到钉钉
"""
import os
import requests
from jenkins import Jenkins

jenkins_url = 'http://192.168.121.130:8080/'
server = Jenkins(jenkins_url, username='admin', password='123456')
job_name = 'job/Api_test'
# job的url就等于jenkins的url+job的url
job_url = jenkins_url + job_name
# 最新一次执行构建的次数
job_last_number = server.get_info(job_name)['lastBuild']['number']
# 测试报告地址
report_url = job_url + str(job_last_number) + '/allure'


def push_message():
    # 获取到 prometheusData.txt文件地址
    file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "allure-report", "export",
                             "prometheusData.txt")
    # 打开文件
    f = open(file_path)
    # 读取文件并转换
    content = {}
    for line in f.readlines():
        # 给line的\n转换后再进行分割
        launch_name = line.strip('\n').split(' ')[0]
        num = line.strip('\n').split(' ')[1]
        # 更新新的变量接收文档内容
        content.update({launch_name: num})
    f.close()  # 关闭文件流
    passed_num = content['launch_status_passed']  # 通过数量
    failed_num = content['launch_status_failed']  # 失败数量
    broken_num = content['launch_status_broken']  # 阻塞的
    skipped_num = content['launch_status_skipped']  # 跳过的
    case_num = content['launch_retries_run']  # 总数量

    """
    钉钉消息发送，通过webhook发送消息
    """
    # webhook = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=2ae85f1c-9f51-40d9-8e07-87cd00f8ea80'
    #
    # new_content = {
    #     "msgtype": "text",
    #     "text": {
    #         "content": "接口自动化测试结果: "
    #                    + "\n构建次数" + str(job_last_number)
    #                    + "\n执行用例总数" + case_num
    #                    + "\n通过数量" + passed_num
    #                    + "\n失败数量" + failed_num
    #                    + "\n阻塞数量" + broken_num
    #                    + "\n跳过数量" + skipped_num
    #                    + "\n构建地址" + job_url
    #                    + "\n报告地址" + job_url+'/allure'
    #
    #     }
    # }
    #
    # result = requests.post(url=webhook, json=new_content)
    # print(result.text)

    """飞书发送通知"""
    webhook = 'https://open.feishu.cn/open-apis/bot/v2/hook/ba9bc6cb-3bcb-4072-93a6-b766182fb403'
    headers = {"Content-Type": "application/json"}
    new_content = {
        "msg_type": "text",
        "content": {
            "text": "接口自动化测试结果: "
                    + "\n构建次数" + str(job_last_number)
                    + "\n执行用例总数" + case_num
                    + "\n通过数量" + passed_num
                    + "\n失败数量" + failed_num
                    + "\n阻塞数量" + broken_num
                    + "\n跳过数量" + skipped_num
                    + "\n构建地址" + job_url
                    + "\n报告地址" + job_url + '/allure'

        }
    }

    result = requests.post(url=webhook, headers=headers, json=new_content)
    print(result.text)


push_message()
